#include "animationtextlineedit.h"

#include <qtimer.h>

AnimationTextLineEdit::AnimationTextLineEdit(QWidget *parent)
    : QLineEdit{parent}
{
    m_aniTimer = new QTimer(this);
    m_aniTimer->setInterval(100);
    connect(m_aniTimer, &QTimer::timeout, this, &AnimationTextLineEdit::slotAniTimerout);
    m_aniTimer->start();
}

void AnimationTextLineEdit::slotAniTimerout()
{
    if (text().isEmpty()) {
        if (m_animationTextList[m_currentIndex].isEmpty())
            setPlaceholderText(m_textList[0]);
        if (!hasFocus()) {
            return;
        }
        showAnimationText();
    }
}

QStringList AnimationTextLineEdit::textList() const
{
    return m_textList;
}

void AnimationTextLineEdit::setTextList(const QStringList &newTextList)
{
    m_textList = newTextList;
    m_animationTextList = generateAnimationTextList(m_textList);
    setPlaceholderText(newTextList[0]);
}

QStringList AnimationTextLineEdit::generateAnimationTextList(QStringList newTextList)
{
    QStringList animationTextList;
    foreach (auto text, newTextList) {
        animationTextList << "";

        int length = text.size();
        for (int i = 0; i < length; ++i) {
            animationTextList << text.left(i);
        }

        for (int i = 0; i < 4; ++i) {
            animationTextList << text;
        }

        for (int i = length; i >0 ; --i) {
            animationTextList << text.left(i);
        }
    }

    return animationTextList;
}

void AnimationTextLineEdit::showAnimationText()
{
    int _tmpindex = m_currentIndex + 1;

    if (_tmpindex >= m_animationTextList.size()) {
        _tmpindex = 0;
    }

    if (_tmpindex <= m_animationTextList.size()) {
        setPlaceholderText(m_animationTextList[_tmpindex]);
    }

    m_currentIndex = _tmpindex;
}
